<template>
  <el-select
    v-model="dicSelect"
    class="select"
    :disabled="inputDisabled"
    :filterable="props.allowCreate || props.filterable"
    :placeholder="calcPlaceholder"
    @change="handleChange"
    @blur="handleBlur"
    clearable
    multiple
  >
    <el-option v-for="item in options"
      :key="item.key"
      :value="item.key"
      :label="item.value"
      :disabled="item.disabled === true"
    />
  </el-select>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
import { useDisabled } from 'element-plus';

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  options: [String, Array],
  filterable: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '--请选择--'
  },
})

const options = ref([]);
const dicSelect = ref([]);
const inputDisabled = useDisabled();

const init = (data) => {
  dicSelect.value = [];
  options.value = [];

  if (data.options) {
    if (Array.isArray(data.options)) {
      options.value = data.options;
    } else if (typeof data.options === 'string') {
      const optionList = [];
      data.options.split(',').forEach(item => {
        optionList.push({key: item, value: item});
      });
      options.value = optionList;
    }

    dicSelect.value = data.modelValue ? data.modelValue.split(',') : [];
  }
};

const handleChange = () => {
  let key = [], resultKey = [], resultValue = [];
  if (dicSelect.value && options.value) {
    key = dicSelect.value;

    options.value.forEach(item => {
      if (key.indexOf(item.key) >= 0) {
        resultKey.push(item.key);
        resultValue.push(item.value);
      }
    });
  }

  emit('update:modelValue', resultKey.join(','), resultValue.join(','));
  emit('change', resultKey.join(','), resultValue.join(','));
};

const handleBlur = () => {
  handleChange();
};

const calcPlaceholder = computed(() => {
  return inputDisabled.value === true ? '' : props.placeholder;
});

watch(() => props, (data) => {
  init(data);
}, {immediate: true, deep: 1});
</script>

<style scoped>
.select {
  width: 100%;
}
</style>